package com.syqc.videos.players

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.*
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.appcompat.widget.AppCompatSeekBar
import androidx.core.view.isVisible
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView
import com.shuyu.gsyvideoplayer.video.base.GSYVideoViewBridge
import com.syqc.monitor.R
import com.syqc.monitor.databinding.PopupMultipleStateBinding
import com.syqc.monitor.databinding.PopupPlayStateBinding
import com.syqc.utils.TimeUtil
import com.syqc.videos.videomanager.TapeManager
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import java.util.concurrent.TimeUnit

class TapeTmnPlayer : StandardGSYVideoPlayer {

    constructor(context: Context, fullFlag: Boolean) : super(context, fullFlag)
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)


    //数据类型
    private var mType: Int = 0

    //是否需要静音
    private var isNeedMute = true

    private var mProgress: Long = 0
    private var maxProgress: Long = 0

    //最大时间
    private var maxStrTime = TimeUtil.zeroHms


    private lateinit var ivSwitchVoice: ImageView
    private lateinit var tvSwitchScale: TextView
    private lateinit var tvTmnTime: TextView
    private lateinit var tvTitle: TextView
    private lateinit var videoProgress: AppCompatSeekBar
    private lateinit var loadingProgress: ProgressBar

    private lateinit var startPlay: ImageView
    private lateinit var tvTmnMultiple: TextView
    private lateinit var tvTmnPlayOperate: TextView
    private lateinit var tvBack: ImageView

    private var listener: com.syqc.videos.interfaces.ITmnListener? = null

    private val mPopup by lazy { MultiplePopup(context) }
    private val mStatePopup by lazy { StatePopup(context) }

    override fun getLayoutId(): Int {
        return R.layout.tape_video_tmn
    }

    override fun init(context: Context?) {
        super.init(context)
        initParams()
        initView()
        setListener()
    }

    private fun initParams() {
        isRotateViewAuto = true
        isLockLand = true
        isReleaseWhenLossAudio = false
        isShowFullAnimation = true
        setIsTouchWiget(false)
        setIsTouchWigetFull(false)

        isNeedMute = true
        TapeManager.instance.isNeedMute = isNeedMute
    }


    private fun initView() {
        ivSwitchVoice = findViewById(R.id.ivSwitchVoice)
        tvSwitchScale = findViewById(R.id.tvSwitchScale)
        tvTmnMultiple = findViewById(R.id.tvTmnMultiple)
        loadingProgress = findViewById(R.id.loadingProgress)
        tvBack = findViewById(R.id.tvBack)
        startPlay = findViewById(R.id.startPlay)
        tvTitle = findViewById(R.id.tvTitle)
        videoProgress = findViewById(R.id.videoProgress)
        tvTmnTime = findViewById(R.id.tvTmnTime)
        tvTmnPlayOperate = findViewById(R.id.tvTmnPlayOperate)

        ivSwitchVoice.isSelected = isNeedMute
    }

    private fun setListener() {
        //声音
        ivSwitchVoice.setOnClickListener {
            isNeedMute = !isNeedMute
            ivSwitchVoice.isSelected = isNeedMute
            TapeManager.instance.isNeedMute = isNeedMute
        }
        //比例
        tvSwitchScale.setOnClickListener {
            if (!mHadPlay) {
                return@setOnClickListener
            }
            when (mType) {
                0 -> mType = 1
                1 -> mType = 2
                2 -> mType = 3
                3 -> mType = 4
                4 -> mType = 0
            }
            resolveTypeUI()
        }
        //倍速
        tvTmnMultiple.setOnClickListener {
            val location = IntArray(2)
            tvTmnMultiple.getLocationOnScreen(location)
            mPopup.showAtLocation(
                tvTmnMultiple, Gravity.NO_GRAVITY,
                location[0], location[1] - measureHeight
            )
        }
        //播放状态
        tvTmnPlayOperate.setOnClickListener {
            val location = IntArray(2)
            tvTmnPlayOperate.getLocationOnScreen(location)
            mStatePopup.showAtLocation(
                tvTmnPlayOperate, Gravity.NO_GRAVITY,
                location[0], location[1] - measureStateHeight
            )
        }
        //返回
        tvBack.setOnClickListener {
            listener?.onBackListener()
        }

        startPlay.setOnClickListener {
            listener?.onPlaying(isInPlayingState)
        }

        videoProgress.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (!mHadPlay) return
                mProgress = progress.toLong()
                tvTmnTime.text = "${TimeUtil.instance.formatLongTime(mProgress)}/$maxStrTime"
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                stopTime()
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                listener?.onSeekProgress(mProgress)
            }
        })
    }

    fun setTmnListener(listener: com.syqc.videos.interfaces.ITmnListener) {
        this.listener = listener
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 设置标题
     *
     * @param title
     */
    fun setTitle(title: String) {
        tvTitle.text = title
    }

    /**
     * Set multiple
     *
     * @param titleId
     */
    fun setMultiple(multiple: Int, isReset: Boolean = false) {
        if (!isReset) listener?.onMultipleListener(multiple)
        val resId = when (multiple) {
            1 -> R.string.desc_video_multiple_one
            2 -> R.string.desc_video_multiple_two
            3 -> R.string.desc_video_multiple_four
            4 -> R.string.desc_video_multiple_eight
            else -> R.string.desc_video_multiple_sixteen
        }
        tvTmnMultiple.setText(resId)
    }

    /**
     *是否正常播放
     */
    fun setPlayState(isNormal: Boolean) {
        if (isNormal) {
            tvTmnPlayOperate.setText(R.string.desc_video_play_normal)
        } else {
            tvTmnPlayOperate.setText(R.string.desc_video_resume_playback)
        }
    }


    ////////////////////////////////////////////////////////////////////////////////////////////


    /**
     * 显示比例
     * 注意，GSYVideoType.setShowType是全局静态生效，除非重启APP。
     */
    private fun resolveTypeUI() {
        if (!mHadPlay) {
            return
        }
        when (mType) {
            1 -> {
                tvSwitchScale.text = "16:9"
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_16_9)
            }

            2 -> {
                tvSwitchScale.text = "4:3"
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_4_3)
            }

            3 -> {
                tvSwitchScale.setText(R.string.desc_video_full_screen)
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL)
            }

            0 -> {
                tvSwitchScale.setText(R.string.desc_video_default_ratio)
                GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT)
            }
        }
        changeTextureViewShowType()
        if (mTextureView != null) mTextureView.requestLayout()
    }


    override fun getGSYVideoManager(): GSYVideoViewBridge {
        TapeManager.instance.initContext(context.applicationContext)
        return TapeManager.instance
    }

    override fun setStateAndUi(state: Int) {
        super.setStateAndUi(state)
        when (state) {
            GSYVideoView.CURRENT_STATE_PLAYING -> {
                startPlay.isVisible = false
            }

            GSYVideoView.CURRENT_STATE_PAUSE,
            GSYVideoView.CURRENT_STATE_AUTO_COMPLETE,
            GSYVideoView.CURRENT_STATE_ERROR -> stopTime()
        }
    }

    override fun touchSurfaceMoveFullLogic(absDeltaX: Float, absDeltaY: Float) {
        super.touchSurfaceMoveFullLogic(absDeltaX, absDeltaY)
        //不给触摸快进，如果需要，屏蔽下方代码即可
        mChangePosition = false

        //不给触摸音量，如果需要，屏蔽下方代码即可
        mChangeVolume = false

        //不给触摸亮度，如果需要，屏蔽下方代码即可
        mBrightness = false
    }

    override fun touchDoubleUp(e: MotionEvent?) {
//        super.touchDoubleUp(e)
    }

    /////////////////////////////////////////////////////////////////////////////////////////////
    fun showStartPlay(isShow: Boolean) {
        startPlay.isVisible = isShow
    }

    /**
     * 是否展示进度
     *
     * @param isShow
     */
    fun showProgress(isShow: Boolean) {
        loadingProgress.isVisible = isShow
        if (isShow) startPlay.isVisible = false
    }

    /**
     * 是否展示倍速
     *
     * @param isShow
     */
    fun isShowMultiple(isShow: Boolean) {
        tvTmnMultiple.isVisible = isShow
    }

    /** 设置seekbar状态 */
    fun setSeekBarState(time: Long) {
        maxProgress = time
        maxStrTime = TimeUtil.instance.formatLongTime(time)
        videoProgress.max = time.toInt()
        videoProgress.progress = 0
        mProgress = 0
        tvTmnTime.text = "${TimeUtil.zeroHms}/$maxStrTime"
    }

    /** 设置seekbar状态 */
    fun setSeekBarProgress(progress: Long, maxTime: Long) {
        maxProgress = maxTime
        mProgress = progress
        maxStrTime = TimeUtil.instance.formatLongTime(maxTime)
        videoProgress.max = maxTime.toInt()
        videoProgress.progress = progress.toInt()
        tvTmnTime.text = "${TimeUtil.instance.formatLongTime(mProgress)}/$maxStrTime"
    }

    private var disposable: Disposable? = null

    fun startTime() {
        stopTime()
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (mProgress >= maxProgress) {
                    listener?.onProgress(mProgress)
                    stopTime()
                }
                videoProgress.progress = mProgress.toInt()
                tvTmnTime.text = "${TimeUtil.instance.formatLongTime(mProgress)}/$maxStrTime"
                mProgress += 1000
            }
    }

    fun stopTime() {
        if (disposable != null && disposable?.isDisposed == false) {
            disposable?.dispose()
            disposable = null
        }
    }
    /////////////////////////////////////////////////////////////////////////////////////////////


    //弹窗View 高度
    private var measureHeight = 0

    /**
     * 倍速弹窗 popup
     *
     * @constructor
     *
     * @param context
     */
    inner class MultiplePopup(context: Context) : PopupWindow() {
        private val binding: PopupMultipleStateBinding =
            PopupMultipleStateBinding.inflate(LayoutInflater.from(context))

        init {
            contentView = binding.root
            isClippingEnabled = false
            contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
            measureHeight = contentView.measuredHeight
            isFocusable = false //popupwindow设置焦点
            isOutsideTouchable = true //点击外面窗口消失
            width = LinearLayout.LayoutParams.WRAP_CONTENT //设置SelectPicPopupWindow弹出窗体的宽
            height = LinearLayout.LayoutParams.WRAP_CONTENT //设置SelectPicPopupWindow弹出窗体的高
            initView()
        }

        fun initView() {
            binding.rdgMultiple.setOnCheckedChangeListener { group, checkedId ->
                if (checkedId == -1) return@setOnCheckedChangeListener
                when (checkedId) {
                    R.id.rdb_multiple_one -> {
                        setMultiple(1)
                    }

                    R.id.rdb_multiple_two -> {
                        setMultiple(2)
                    }

                    R.id.rdb_multiple_four -> {
                        setMultiple(3)
                    }

                    R.id.rdb_multiple_eight -> {
                        setMultiple(4)
                    }

                    R.id.rdb_multiple_sixteen -> {
                        setMultiple(5)
                    }
                }
                dismiss()
                group.clearCheck()
            }
        }
    }

    private var measureStateHeight = 0

    inner class StatePopup(context: Context) : PopupWindow() {
        private val binding = PopupPlayStateBinding.inflate(LayoutInflater.from(context))

        init {
            contentView = binding.root
            isClippingEnabled = false
            contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
            measureStateHeight = contentView.measuredHeight
            isFocusable = false //popupwindow设置焦点
            isOutsideTouchable = true //点击外面窗口消失
            width = LinearLayout.LayoutParams.WRAP_CONTENT //设置SelectPicPopupWindow弹出窗体的宽
            height = LinearLayout.LayoutParams.WRAP_CONTENT //设置SelectPicPopupWindow弹出窗体的高
            initView()
        }

        fun initView() {
            binding.rdgPlayState.setOnCheckedChangeListener { group, checkedId ->
                if (checkedId == -1) return@setOnCheckedChangeListener
                when (checkedId) {
                    R.id.rdb_play_state_pause -> listener?.onPlayState(com.syqc.videos.interfaces.PlayState.PAUSE)
                    R.id.rdb_play_state_fast -> listener?.onPlayState(com.syqc.videos.interfaces.PlayState.FAST)
                    R.id.rdb_play_state_slow -> listener?.onPlayState(com.syqc.videos.interfaces.PlayState.BACK)
                    R.id.rdb_play_state_frame -> listener?.onPlayState(com.syqc.videos.interfaces.PlayState.FRAME)
                }
                group.clearCheck()
                dismiss()
            }
        }
    }
}